package it.univaq.mwt.xml.epubmanager.presentation;

import it.univaq.mwt.xml.epubmanager.business.model.Metadata;
import it.univaq.mwt.xml.epubmanager.common.ValidationUtility;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

/**
 *
 * @author Sonia
 */
@Component
public class FormMetadataValidator implements Validator {

    @Override
    public boolean supports(Class<?> klass) {
        return Metadata.class.isAssignableFrom(klass);
    }

    @Override
    public void validate(Object o, Errors errors) {

        Metadata metadata = (Metadata) o;

        //controllo campi obbligatori
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "title", "errors.required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "language", "errors.required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "creator", "errors.required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "isbn", "errors.required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "date", "errors.date");


        //controlli sulla lunghezza dei campi
        ValidationUtility.rejectIfMaxLength(errors, "title", "errors.maxlength", metadata.getTitle(), 255);
        ValidationUtility.rejectIfMaxLength(errors, "creator", "errors.maxlength", metadata.getCreator(), 255);
        ValidationUtility.rejectIfMaxLength(errors, "publisher", "errors.maxlength", metadata.getPublisher(), 255);       
        ValidationUtility.rejectIfMaxLength(errors, "contributor", "errors.maxlength", metadata.getPublisher(), 255);
        ValidationUtility.rejectIfMaxLength(errors, "language", "errors.maxlength", metadata.getLanguage(), 2);
        ValidationUtility.rejectIfMaxLength(errors, "isbn", "errors.maxlength", metadata.getIsbn(), 13);
        ValidationUtility.rejectIfMinLength(errors, "identifier", "errors.minlength", metadata.getIsbn(), 13);
	//fine controlli sulla lunghezza dei campi

        //inizio controlli sulla consistenza dei campi
        ValidationUtility.rejectIfAccented(errors, "title", "errors.accent", metadata.getTitle());
        ValidationUtility.rejectIfAccented(errors, "contributor", "errors.accent", metadata.getContributor());
        ValidationUtility.rejectIfAccented(errors, "creator", "errors.accent", metadata.getCreator());
        ValidationUtility.rejectIfMaxLength(errors, "contributor", "errors.maxlength", metadata.getPublisher(), 255);
        ValidationUtility.rejectIfAccented(errors, "publisher", "errors.accent", metadata.getPublisher());

	//fine controllo sulla consistrnza dei campi

        //controllo sulla lingua
        ValidationUtility.rejectIfNal(errors, "language", "errors.linguedisponibili", metadata.getLanguage());
	//fine controllo sulla lingua

    }

}
